
<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>cleverhans.attacks.fast_gradient_method &#8212; CleverHans  documentation</title>
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/alabaster.css" type="text/css" />
    <script id="documentation_options" data-url_root="../../../" src="../../../_static/documentation_options.js"></script>
    <script src="../../../_static/jquery.js"></script>
    <script src="../../../_static/underscore.js"></script>
    <script src="../../../_static/doctools.js"></script>
    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />
   
  <link rel="stylesheet" href="../../../_static/custom.css" type="text/css" />
  
  
  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

  </head><body>
  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          

          <div class="body" role="main">
            
  <h1>Source code for cleverhans.attacks.fast_gradient_method</h1><div class="highlight"><pre>
<span></span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">The FastGradientMethod attack.</span>
<span class="sd">&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">warnings</span>

<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">tensorflow</span> <span class="k">as</span> <span class="nn">tf</span>

<span class="kn">from</span> <span class="nn">cleverhans.attacks.attack</span> <span class="kn">import</span> <span class="n">Attack</span>
<span class="kn">from</span> <span class="nn">cleverhans.compat</span> <span class="kn">import</span> <span class="n">reduce_max</span><span class="p">,</span> <span class="n">reduce_sum</span><span class="p">,</span> <span class="n">softmax_cross_entropy_with_logits</span>
<span class="kn">from</span> <span class="nn">cleverhans</span> <span class="kn">import</span> <span class="n">utils_tf</span>


<div class="viewcode-block" id="FastGradientMethod"><a class="viewcode-back" href="../../../source/attacks.html#cleverhans.attacks.FastGradientMethod">[docs]</a><span class="k">class</span> <span class="nc">FastGradientMethod</span><span class="p">(</span><span class="n">Attack</span><span class="p">):</span>
  <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">  This attack was originally implemented by Goodfellow et al. (2014) with the</span>
<span class="sd">  infinity norm (and is known as the &quot;Fast Gradient Sign Method&quot;). This</span>
<span class="sd">  implementation extends the attack to other norms, and is therefore called</span>
<span class="sd">  the Fast Gradient Method.</span>
<span class="sd">  Paper link: https://arxiv.org/abs/1412.6572</span>

<span class="sd">  :param model: cleverhans.model.Model</span>
<span class="sd">  :param sess: optional tf.Session</span>
<span class="sd">  :param dtypestr: dtype of the data</span>
<span class="sd">  :param kwargs: passed through to super constructor</span>
<span class="sd">  &quot;&quot;&quot;</span>

  <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="n">sess</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">dtypestr</span><span class="o">=</span><span class="s1">&#39;float32&#39;</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Create a FastGradientMethod instance.</span>
<span class="sd">    Note: the model parameter should be an instance of the</span>
<span class="sd">    cleverhans.model.Model abstraction provided by CleverHans.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="nb">super</span><span class="p">(</span><span class="n">FastGradientMethod</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">sess</span><span class="p">,</span> <span class="n">dtypestr</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">feedable_kwargs</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;eps&#39;</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">,</span> <span class="s1">&#39;y_target&#39;</span><span class="p">,</span> <span class="s1">&#39;clip_min&#39;</span><span class="p">,</span> <span class="s1">&#39;clip_max&#39;</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">structural_kwargs</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;ord&#39;</span><span class="p">,</span> <span class="s1">&#39;sanity_checks&#39;</span><span class="p">,</span> <span class="s1">&#39;clip_grad&#39;</span><span class="p">,</span> <span class="s1">&#39;loss_fn&#39;</span><span class="p">]</span>

<div class="viewcode-block" id="FastGradientMethod.generate"><a class="viewcode-back" href="../../../source/attacks.html#cleverhans.attacks.FastGradientMethod.generate">[docs]</a>  <span class="k">def</span> <span class="nf">generate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Returns the graph for Fast Gradient Method adversarial examples.</span>

<span class="sd">    :param x: The model&#39;s symbolic inputs.</span>
<span class="sd">    :param kwargs: See `parse_params`</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c1"># Parse and save attack-specific parameters</span>
    <span class="k">assert</span> <span class="bp">self</span><span class="o">.</span><span class="n">parse_params</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="n">labels</span><span class="p">,</span> <span class="n">_nb_classes</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_or_guess_labels</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">fgm</span><span class="p">(</span>
        <span class="n">x</span><span class="p">,</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">get_logits</span><span class="p">(</span><span class="n">x</span><span class="p">),</span>
        <span class="n">y</span><span class="o">=</span><span class="n">labels</span><span class="p">,</span>
        <span class="n">eps</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">eps</span><span class="p">,</span>
        <span class="nb">ord</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">ord</span><span class="p">,</span>
        <span class="n">loss_fn</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">loss_fn</span><span class="p">,</span>
        <span class="n">clip_min</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span><span class="p">,</span>
        <span class="n">clip_max</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span><span class="p">,</span>
        <span class="n">clip_grad</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_grad</span><span class="p">,</span>
        <span class="n">targeted</span><span class="o">=</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">y_target</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">),</span>
        <span class="n">sanity_checks</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">sanity_checks</span><span class="p">)</span></div>

<div class="viewcode-block" id="FastGradientMethod.parse_params"><a class="viewcode-back" href="../../../source/attacks.html#cleverhans.attacks.FastGradientMethod.parse_params">[docs]</a>  <span class="k">def</span> <span class="nf">parse_params</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span>
                   <span class="n">eps</span><span class="o">=</span><span class="mf">0.3</span><span class="p">,</span>
                   <span class="nb">ord</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">inf</span><span class="p">,</span>
                   <span class="n">loss_fn</span><span class="o">=</span><span class="n">softmax_cross_entropy_with_logits</span><span class="p">,</span>
                   <span class="n">y</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                   <span class="n">y_target</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                   <span class="n">clip_min</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                   <span class="n">clip_max</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                   <span class="n">clip_grad</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
                   <span class="n">sanity_checks</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
                   <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Take in a dictionary of parameters and applies attack-specific checks</span>
<span class="sd">    before saving them as attributes.</span>

<span class="sd">    Attack-specific parameters:</span>

<span class="sd">    :param eps: (optional float) attack step size (input variation)</span>
<span class="sd">    :param ord: (optional) Order of the norm (mimics NumPy).</span>
<span class="sd">                Possible values: np.inf, 1 or 2.</span>
<span class="sd">    :param loss_fn: Loss function that takes (labels, logits) as arguments and returns loss</span>
<span class="sd">    :param y: (optional) A tensor with the true labels. Only provide</span>
<span class="sd">              this parameter if you&#39;d like to use true labels when crafting</span>
<span class="sd">              adversarial samples. Otherwise, model predictions are used as</span>
<span class="sd">              labels to avoid the &quot;label leaking&quot; effect (explained in this</span>
<span class="sd">              paper: https://arxiv.org/abs/1611.01236). Default is None.</span>
<span class="sd">              Labels should be one-hot-encoded.</span>
<span class="sd">    :param y_target: (optional) A tensor with the labels to target. Leave</span>
<span class="sd">                     y_target=None if y is also set. Labels should be</span>
<span class="sd">                     one-hot-encoded.</span>
<span class="sd">    :param clip_min: (optional float) Minimum input component value</span>
<span class="sd">    :param clip_max: (optional float) Maximum input component value</span>
<span class="sd">    :param clip_grad: (optional bool) Ignore gradient components</span>
<span class="sd">                      at positions where the input is already at the boundary</span>
<span class="sd">                      of the domain, and the update step will get clipped out.</span>
<span class="sd">    :param sanity_checks: bool, if True, include asserts</span>
<span class="sd">      (Turn them off to use less runtime / memory or for unit tests that</span>
<span class="sd">      intentionally pass strange input)</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c1"># Save attack-specific parameters</span>

    <span class="bp">self</span><span class="o">.</span><span class="n">eps</span> <span class="o">=</span> <span class="n">eps</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">ord</span> <span class="o">=</span> <span class="nb">ord</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">loss_fn</span> <span class="o">=</span> <span class="n">loss_fn</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">y</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">y_target</span> <span class="o">=</span> <span class="n">y_target</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span> <span class="o">=</span> <span class="n">clip_min</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span> <span class="o">=</span> <span class="n">clip_max</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">clip_grad</span> <span class="o">=</span> <span class="n">clip_grad</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">sanity_checks</span> <span class="o">=</span> <span class="n">sanity_checks</span>

    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">y_target</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
      <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Must not set both y and y_target&quot;</span><span class="p">)</span>
    <span class="c1"># Check if order of the norm is acceptable given current implementation</span>
    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">ord</span> <span class="ow">not</span> <span class="ow">in</span> <span class="p">[</span><span class="n">np</span><span class="o">.</span><span class="n">inf</span><span class="p">,</span> <span class="nb">int</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="nb">int</span><span class="p">(</span><span class="mi">2</span><span class="p">)]:</span>
      <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Norm order must be either np.inf, 1, or 2.&quot;</span><span class="p">)</span>

    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_grad</span> <span class="ow">and</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">clip_min</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">or</span> <span class="bp">self</span><span class="o">.</span><span class="n">clip_max</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">):</span>
      <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Must set clip_min and clip_max if clip_grad is set&quot;</span><span class="p">)</span>

    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">kwargs</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
      <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;kwargs is unused and will be removed on or after &quot;</span>
                    <span class="s2">&quot;2019-04-26.&quot;</span><span class="p">)</span>

    <span class="k">return</span> <span class="kc">True</span></div></div>


<div class="viewcode-block" id="fgm"><a class="viewcode-back" href="../../../source/attacks.html#cleverhans.attacks.fgm">[docs]</a><span class="k">def</span> <span class="nf">fgm</span><span class="p">(</span><span class="n">x</span><span class="p">,</span>
        <span class="n">logits</span><span class="p">,</span>
        <span class="n">y</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">eps</span><span class="o">=</span><span class="mf">0.3</span><span class="p">,</span>
        <span class="nb">ord</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">inf</span><span class="p">,</span>
        <span class="n">loss_fn</span><span class="o">=</span><span class="n">softmax_cross_entropy_with_logits</span><span class="p">,</span>
        <span class="n">clip_min</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">clip_max</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">clip_grad</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
        <span class="n">targeted</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
        <span class="n">sanity_checks</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
  <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">  TensorFlow implementation of the Fast Gradient Method.</span>
<span class="sd">  :param x: the input placeholder</span>
<span class="sd">  :param logits: output of model.get_logits</span>
<span class="sd">  :param y: (optional) A placeholder for the true labels. If targeted</span>
<span class="sd">            is true, then provide the target label. Otherwise, only provide</span>
<span class="sd">            this parameter if you&#39;d like to use true labels when crafting</span>
<span class="sd">            adversarial samples. Otherwise, model predictions are used as</span>
<span class="sd">            labels to avoid the &quot;label leaking&quot; effect (explained in this</span>
<span class="sd">            paper: https://arxiv.org/abs/1611.01236). Default is None.</span>
<span class="sd">            Labels should be one-hot-encoded.</span>
<span class="sd">  :param eps: the epsilon (input variation parameter)</span>
<span class="sd">  :param ord: (optional) Order of the norm (mimics NumPy).</span>
<span class="sd">              Possible values: np.inf, 1 or 2.</span>
<span class="sd">  :param loss_fn: Loss function that takes (labels, logits) as arguments and returns loss</span>
<span class="sd">  :param clip_min: Minimum float value for adversarial example components</span>
<span class="sd">  :param clip_max: Maximum float value for adversarial example components</span>
<span class="sd">  :param clip_grad: (optional bool) Ignore gradient components</span>
<span class="sd">                    at positions where the input is already at the boundary</span>
<span class="sd">                    of the domain, and the update step will get clipped out.</span>
<span class="sd">  :param targeted: Is the attack targeted or untargeted? Untargeted, the</span>
<span class="sd">                   default, will try to make the label incorrect. Targeted</span>
<span class="sd">                   will instead try to move in the direction of being more</span>
<span class="sd">                   like y.</span>
<span class="sd">  :return: a tensor for the adversarial example</span>
<span class="sd">  &quot;&quot;&quot;</span>

  <span class="n">asserts</span> <span class="o">=</span> <span class="p">[]</span>

  <span class="c1"># If a data range was specified, check that the input was in that range</span>
  <span class="k">if</span> <span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
    <span class="n">asserts</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">utils_tf</span><span class="o">.</span><span class="n">assert_greater_equal</span><span class="p">(</span>
        <span class="n">x</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">clip_min</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">)))</span>

  <span class="k">if</span> <span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
    <span class="n">asserts</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">utils_tf</span><span class="o">.</span><span class="n">assert_less_equal</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">tf</span><span class="o">.</span><span class="n">cast</span><span class="p">(</span><span class="n">clip_max</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">dtype</span><span class="p">)))</span>

  <span class="c1"># Make sure the caller has not passed probs by accident</span>
  <span class="k">assert</span> <span class="n">logits</span><span class="o">.</span><span class="n">op</span><span class="o">.</span><span class="n">type</span> <span class="o">!=</span> <span class="s1">&#39;Softmax&#39;</span>

  <span class="k">if</span> <span class="n">y</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="c1"># Using model predictions as ground truth to avoid label leaking</span>
    <span class="n">preds_max</span> <span class="o">=</span> <span class="n">reduce_max</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="n">y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">to_float</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">equal</span><span class="p">(</span><span class="n">logits</span><span class="p">,</span> <span class="n">preds_max</span><span class="p">))</span>
    <span class="n">y</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">stop_gradient</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>
  <span class="n">y</span> <span class="o">=</span> <span class="n">y</span> <span class="o">/</span> <span class="n">reduce_sum</span><span class="p">(</span><span class="n">y</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

  <span class="c1"># Compute loss</span>
  <span class="n">loss</span> <span class="o">=</span> <span class="n">loss_fn</span><span class="p">(</span><span class="n">labels</span><span class="o">=</span><span class="n">y</span><span class="p">,</span> <span class="n">logits</span><span class="o">=</span><span class="n">logits</span><span class="p">)</span>
  <span class="k">if</span> <span class="n">targeted</span><span class="p">:</span>
    <span class="n">loss</span> <span class="o">=</span> <span class="o">-</span><span class="n">loss</span>

  <span class="c1"># Define gradient of loss wrt input</span>
  <span class="n">grad</span><span class="p">,</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">gradients</span><span class="p">(</span><span class="n">loss</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>

  <span class="k">if</span> <span class="n">clip_grad</span><span class="p">:</span>
    <span class="n">grad</span> <span class="o">=</span> <span class="n">utils_tf</span><span class="o">.</span><span class="n">zero_out_clipped_grads</span><span class="p">(</span><span class="n">grad</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">clip_min</span><span class="p">,</span> <span class="n">clip_max</span><span class="p">)</span>

  <span class="n">optimal_perturbation</span> <span class="o">=</span> <span class="n">optimize_linear</span><span class="p">(</span><span class="n">grad</span><span class="p">,</span> <span class="n">eps</span><span class="p">,</span> <span class="nb">ord</span><span class="p">)</span>

  <span class="c1"># Add perturbation to original example to obtain adversarial example</span>
  <span class="n">adv_x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">optimal_perturbation</span>

  <span class="c1"># If clipping is needed, reset all values outside of [clip_min, clip_max]</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">)</span> <span class="ow">or</span> <span class="p">(</span><span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">):</span>
    <span class="c1"># We don&#39;t currently support one-sided clipping</span>
    <span class="k">assert</span> <span class="n">clip_min</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">clip_max</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
    <span class="n">adv_x</span> <span class="o">=</span> <span class="n">utils_tf</span><span class="o">.</span><span class="n">clip_by_value</span><span class="p">(</span><span class="n">adv_x</span><span class="p">,</span> <span class="n">clip_min</span><span class="p">,</span> <span class="n">clip_max</span><span class="p">)</span>

  <span class="k">if</span> <span class="n">sanity_checks</span><span class="p">:</span>
    <span class="k">with</span> <span class="n">tf</span><span class="o">.</span><span class="n">control_dependencies</span><span class="p">(</span><span class="n">asserts</span><span class="p">):</span>
      <span class="n">adv_x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">identity</span><span class="p">(</span><span class="n">adv_x</span><span class="p">)</span>

  <span class="k">return</span> <span class="n">adv_x</span></div>


<div class="viewcode-block" id="optimize_linear"><a class="viewcode-back" href="../../../source/attacks.html#cleverhans.attacks.optimize_linear">[docs]</a><span class="k">def</span> <span class="nf">optimize_linear</span><span class="p">(</span><span class="n">grad</span><span class="p">,</span> <span class="n">eps</span><span class="p">,</span> <span class="nb">ord</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">inf</span><span class="p">):</span>
  <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">  Solves for the optimal input to a linear function under a norm constraint.</span>

<span class="sd">  Optimal_perturbation = argmax_{eta, ||eta||_{ord} &lt; eps} dot(eta, grad)</span>

<span class="sd">  :param grad: tf tensor containing a batch of gradients</span>
<span class="sd">  :param eps: float scalar specifying size of constraint region</span>
<span class="sd">  :param ord: int specifying order of norm</span>
<span class="sd">  :returns:</span>
<span class="sd">    tf tensor containing optimal perturbation</span>
<span class="sd">  &quot;&quot;&quot;</span>

  <span class="c1"># In Python 2, the `list` call in the following line is redundant / harmless.</span>
  <span class="c1"># In Python 3, the `list` call is needed to convert the iterator returned by `range` into a list.</span>
  <span class="n">red_ind</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">grad</span><span class="o">.</span><span class="n">get_shape</span><span class="p">())))</span>
  <span class="n">avoid_zero_div</span> <span class="o">=</span> <span class="mf">1e-12</span>
  <span class="k">if</span> <span class="nb">ord</span> <span class="o">==</span> <span class="n">np</span><span class="o">.</span><span class="n">inf</span><span class="p">:</span>
    <span class="c1"># Take sign of gradient</span>
    <span class="n">optimal_perturbation</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="n">grad</span><span class="p">)</span>
    <span class="c1"># The following line should not change the numerical results.</span>
    <span class="c1"># It applies only because `optimal_perturbation` is the output of</span>
    <span class="c1"># a `sign` op, which has zero derivative anyway.</span>
    <span class="c1"># It should not be applied for the other norms, where the</span>
    <span class="c1"># perturbation has a non-zero derivative.</span>
    <span class="n">optimal_perturbation</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">stop_gradient</span><span class="p">(</span><span class="n">optimal_perturbation</span><span class="p">)</span>
  <span class="k">elif</span> <span class="nb">ord</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
    <span class="n">abs_grad</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">abs</span><span class="p">(</span><span class="n">grad</span><span class="p">)</span>
    <span class="n">sign</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="n">grad</span><span class="p">)</span>
    <span class="n">max_abs_grad</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_max</span><span class="p">(</span><span class="n">abs_grad</span><span class="p">,</span> <span class="n">red_ind</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="n">tied_for_max</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">to_float</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">equal</span><span class="p">(</span><span class="n">abs_grad</span><span class="p">,</span> <span class="n">max_abs_grad</span><span class="p">))</span>
    <span class="n">num_ties</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_sum</span><span class="p">(</span><span class="n">tied_for_max</span><span class="p">,</span> <span class="n">red_ind</span><span class="p">,</span> <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="n">optimal_perturbation</span> <span class="o">=</span> <span class="n">sign</span> <span class="o">*</span> <span class="n">tied_for_max</span> <span class="o">/</span> <span class="n">num_ties</span>
  <span class="k">elif</span> <span class="nb">ord</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
    <span class="n">square</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">maximum</span><span class="p">(</span><span class="n">avoid_zero_div</span><span class="p">,</span>
                        <span class="n">reduce_sum</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">square</span><span class="p">(</span><span class="n">grad</span><span class="p">),</span>
                                   <span class="n">reduction_indices</span><span class="o">=</span><span class="n">red_ind</span><span class="p">,</span>
                                   <span class="n">keepdims</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>
    <span class="n">optimal_perturbation</span> <span class="o">=</span> <span class="n">grad</span> <span class="o">/</span> <span class="n">tf</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">square</span><span class="p">)</span>
  <span class="k">else</span><span class="p">:</span>
    <span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">(</span><span class="s2">&quot;Only L-inf, L1 and L2 norms are &quot;</span>
                              <span class="s2">&quot;currently implemented.&quot;</span><span class="p">)</span>

  <span class="c1"># Scale perturbation to be the solution for the norm=eps rather than</span>
  <span class="c1"># norm=1 problem</span>
  <span class="n">scaled_perturbation</span> <span class="o">=</span> <span class="n">utils_tf</span><span class="o">.</span><span class="n">mul</span><span class="p">(</span><span class="n">eps</span><span class="p">,</span> <span class="n">optimal_perturbation</span><span class="p">)</span>
  <span class="k">return</span> <span class="n">scaled_perturbation</span></div>
</pre></div>

          </div>
          
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<h1 class="logo"><a href="../../../index.html">CleverHans</a></h1>








<h3>Navigation</h3>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../source/attacks.html"><cite>attacks</cite> module</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../source/model.html"><cite>model</cite> module</a></li>
</ul>

<div class="relations">
<h3>Related Topics</h3>
<ul>
  <li><a href="../../../index.html">Documentation overview</a><ul>
  <li><a href="../../index.html">Module code</a><ul>
  </ul></li>
  </ul></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
  <h3 id="searchlabel">Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>
    </div>
</div>
<script>$('#searchbox').show(0);</script>








        </div>
      </div>
      <div class="clearer"></div>
    </div>


  </body>
</html>